<?php

class HTech_Controller_Plugin_Authenticate extends Zend_Controller_Plugin_Abstract
{
    /*
     * Validates resource requests
     * 1. non-valid requests from authenticated users are re-routed to auth.index.deny
     * 2. all requests from non-authenticated user are re-routed to auth.index.login
     *    unless the requested resource is an open one - see config.ini's open_resources section
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $module = $request->getModuleName();
        $controller = $request->getControllerName();
        $action = $request->getActionName();
        $resource = sprintf('%s.%s.%s', $module, $controller, $action);
        $identity = Zend_Auth::getInstance()->getIdentity();
        
        if($identity) {   
            if(!isset($identity->resources[$resource])) {
                $request->setModuleName('default')->setControllerName('auth')->setActionName('deny');
            }
        } else {
            $conf = new Zend_Config_Ini(APPLICATION_PATH . '/configs/config.ini');
            if(!isset($conf->open_resources->$module->$controller->$action))
                $request->setModuleName('default')->setControllerName('auth')->setActionName('login'); 
        }
        /*
        if(!$identity->resources[$resource]) {
            if($identity->Username) {
                $request->setModuleName('default')->setControllerName('auth')->setActionName('deny');
            } else {            
                $request->setModuleName('default')->setControllerName('auth')->setActionName('login');
            }
        } 
         * 
         */    

        set_include_path(get_include_path() . PATH_SEPARATOR . 
                APPLICATION_PATH . DIRECTORY_SEPARATOR . 'modules' . 
                DIRECTORY_SEPARATOR . $request->getModuleName() . 
                DIRECTORY_SEPARATOR . 'models'); 
    }
}